#include "../creditutility.h"
#include <iostream>
#include <QFile>
#include <QProcess>
#include <QList>
#include <QtNetwork/QNetworkInterface>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>

QString getMac() {
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();

    int nCnt = nets.count();
    QString strMacAddr = "";
    for(int i = 0; i < nCnt; i++)
    {
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) &&
            nets[i].flags().testFlag(QNetworkInterface::IsRunning) &&
            !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            for(int j = 0; j < nets[i].addressEntries().size(); j++)
            {
                if(nets[i].addressEntries().at(j).ip() != QHostAddress::LocalHost &&
                    nets[i].addressEntries().at(j).ip().protocol() == QAbstractSocket::IPv4Protocol)
                {
                    strMacAddr = nets[i].hardwareAddress();
                }
            }
        }
    }

    return strMacAddr;
}

MODE mode;
int main(int argc, char *argv[])
{
    if(argc > 1) {
        std::cout << "Input password:" << std::endl;
        std::string _password;
        std::cin >> _password;
        QString password = QString::fromStdString(_password);
        if(password != modeSelKey) {
            std::cout << "Wrong Password!" << std::endl;
        } else {
            for(int ind = 1; ind < argc; ind++) {
                if(QString(argv[ind]) == "RO") mode = MODE(mode | ResultOverview);
                if(QString(argv[ind]) == "EA") mode = MODE(mode | EditActivity);
                if(QString(argv[ind]) == "QR") mode = MODE(mode | QueryResult);
                if(QString(argv[ind]) == "FA") mode = FullAccess;
            }
            QJsonObject result;
            result.insert("mac", getMac());
            result.insert("mode", mode);

            QJsonDocument doc;
            doc.setObject(result);
            QFile settings("settings");
            settings.open(QIODevice::WriteOnly | QIODevice::Truncate);
            settings.write(encrypt(doc.toJson(QJsonDocument::Compact)));
            settings.close();
            std::cout << "Mode changed!" << std::endl;
        }
    }
    return 0;
}
